package com.xuecheng.learning.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.model.vo.TeachplanVo;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.feignclient.MediaServiceClient;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.service.LearningService;
import com.xuecheng.learning.service.MyCourseTablesService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class LearningServiceImpl implements LearningService {

    @Autowired
    private MyCourseTablesService courseTablesService;

    @Autowired
    private ContentServiceClient contentServiceClient;

    @Autowired
    private MediaServiceClient mediaServiceClient;

    /**
     * @description 获取教学视频
     * @param courseId 课程id
     * @param teachplanId 课程计划id
     * @param mediaId 视频文件id
     * @return com.xuecheng.base.model.RestResponse<java.lang.String>
     * @author Mr.M
     * @date 2022/10/5 9:08
     */
    @Override
    public RestResponse<String> getVideo(String userId, Long courseId, Long teachplanId, String mediaId) {

        // 查询课程信息
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        // 判断如果为null不再继续
        if(coursepublish == null) {
            return RestResponse.validfail("课程不存在");
        }

        // 远程调用内容管理服务根据课程计划id（teachplanId）去查询课程机会信息，如果is_preview的值为1表示支持试学
        // 也可以从coursepublish对象中解析出课程计划信息去判断是否支持试学
        // 如果支持试学调用媒资服务查询视频的播放地址，返回
        String teachplanJson = coursepublish.getTeachplan();
        List<TeachplanVo> teachplanVos = JSON.parseArray(teachplanJson, TeachplanVo.class); // 把json串转成List
        // 把所有小章节添加到集合中
        List<TeachplanVo> teachplanTreeNodesList = new ArrayList<>();
        teachplanVos.forEach(teachplanVo -> {
            // 遍历大章节
            List<TeachplanVo> teachPlanTreeNodes = teachplanVo.getTeachPlanTreeNodes();
            teachPlanTreeNodes.forEach(t -> {
                teachplanTreeNodesList.add(t);
            });
        });

        // 转化为map方便自己获取
        Map<Long, TeachplanVo> teachplanVoMap = teachplanTreeNodesList.stream().collect(Collectors.toMap(TeachplanVo::getId, t -> t));
        TeachplanVo teachplanVo = teachplanVoMap.get(teachplanId);
        if(teachplanVo == null) {
            XueChengPlusException.cast("该章节没有视频");
        }
        String isPreview = teachplanVo.getIsPreview();
        // 1表示支持试看
        if("1".equals(isPreview)) {
            // 远程调用媒资获取视频播放地址
            RestResponse<String> restResponse = mediaServiceClient.getPlayUrlByMediaId(mediaId);
            return restResponse;
        }

        // 用户已登录
        if(StringUtils.isNotEmpty(userId)) {
            // 获取学习资格
            XcCourseTablesDto learningStatus = courseTablesService.getLearningStatus(userId, courseId);
            String learnStatus = learningStatus.getLearnStatus();
            if("702002".equals(learnStatus)) {
                return RestResponse.validfail("无法学习，因为没有选课或选课后没有支付");
            } else if ("702003".equals(learnStatus)) {
                return RestResponse.validfail("已过期需要申请续期或重新支付");
            } else {
                // 有资格学习，要返回视频的播放地址
                // 远程调用媒资服务获取视频的播放地址
                RestResponse<String> playUrlByMediaId = mediaServiceClient.getPlayUrlByMediaId(mediaId);
                return playUrlByMediaId;
            }
        }

        // 如果用户没有登录
        // 取出课程的收费规则
        String charge = coursepublish.getCharge();
        if("201000".equals(charge)) {
            // 有资格学习，要返回视频的播放地址
            // 远程调用媒资服务获取视频的播放地址
            RestResponse<String> playUrlByMediaId = mediaServiceClient.getPlayUrlByMediaId(mediaId);
            return playUrlByMediaId;
        }

        return RestResponse.validfail("该课程没有选课");
    }
}
